<?php
/**
 * Project: Espolon
 * Licence: BSD License
 * Link: http://espolon.org/
 * Copyright: Nicolas de Bari Embriz Garcia Rojas <nbari at pobox dot com>
 * Author: Nicolas de Bari Embriz Garcia Rojas <nbari at pobox dot com>
 * Version: Beta
 */

if (!defined('SITE_ROOT')) exit('No direct script access allowed');

/**
 * Save status of modules
 */
if (isset($_POST['modules']) OR $options[0] == 'save_status') {
  $rs = $db->Execute("UPDATE core_modules SET status='0'");
  if (isset($_POST['modules'])) {
    foreach ($_POST['modules'] as $value) {
      $rs = $db->Execute("UPDATE core_modules SET status='1' WHERE name='$value'");
    }
  }
  /**
   * update perms for avoiding problems when adding new modules
   */
	$dir = SITE_ROOT.'modules';
	$files = $db->GetCol("SELECT name FROM core_modules WHERE status=1"); // Active modules
	$modules = array();
	foreach ($files as $data) {
		$inc = "$dir/$data/$data"."_module.php";
		if (file_exists($inc)) {
			require_once $inc;
			$modules[$data]['name'] = $data;
			$modules[$data]['description'] = trim($module_description);
			$modules[$data]['perms'] = $module_perms;
			$module_description = '';
			$module_perms = '';
		}
	}
	if (empty($modules)) {
    $admin_perms = null;
  } else {
	/**
	 * Set perms for ADMIN rid 3
	 */
	  foreach ($modules as $key => $value) {
		  $admin_perms[$key] = $value['perms'];
	  }
	  $rs = $db->GetOne('SELECT perms from core_permissions WHERE rid=3');
	  if ($rs != serialize($admin_perms)) {
		  $d_admin['rid'] = 3;
		  $d_admin['perms'] = serialize($admin_perms);
		  $rs = @$db->AutoExecute('core_permissions', $d_admin, 'INSERT');
		  if(!$rs) {
			  $rs = $db->AutoExecute('core_permissions', $d_admin, 'UPDATE', 'rid=3');
		  }
		  $db->CacheFlush();
	  }
	}
  /**
   * Redirect for view enable/diabled modules
   */
  header('refresh: 0; url=/admin/modules');
}

$tpl->assign('modules_options', array('default_commands', 'groups'));
$tpl->assign('active', $options[0]);

$option = isset($options[0]) ? $options[0] : null;

switch($option) {
  case 'default_commands':
    if (isset($_POST['action'])) {
      $values = explode('|', $_POST['action']);
      $data['config_name'] = "default_command_$values[0]";
      $data['config_value'] = ($values[1] == 'none') ? null : $values[1];
      $rs = @$db->AutoExecute('core_config', $data, 'INSERT');
      if(!$rs) {
        $rs = $db->AutoExecute('core_config', $data, 'UPDATE', "config_name='$data[config_name]'");
      }
      $db->CacheFlush();
    }
    $tpl->assign('active', $options[0]);
    $tpl->assign('option_tpl',"$template/modules/$module/modules_commands.tpl");
    $rs = $db->GetCol("SELECT name FROM core_modules WHERE name NOT IN ('main','user','admin') AND status=1 ORDER BY name");
    $dir = SITE_ROOT.'modules';
    $modules = array();
    foreach ($rs as $value) {
      $inc = "$dir/$value/$value"."_module.php";
      if (file_exists($inc)) {
        require_once $inc;
        $perms = ($rs2 = $db->GetOne("SELECT config_value FROM core_config WHERE config_name='default_command_$value'")) ? array('default' => $rs2) : array('default' => _('Select'));
        foreach($module_perms as $perm) {
          if($rs2 != $perm) {
            $perms[$perm] = $perm;
          }
        }
        if($perms['default'] != _('Select')) {
          $perms[''] = _('none');
        }
        $modules[$value] = array(trim($module_description) => $perms);
        $perms = array();
        $module_description = null;
      }
    }
    $tpl->assign('modules', $modules);
  break;
  case 'groups':
    $mod = new Modules();
    $tpl->assign('option_tpl',"$template/modules/$module/add_module_group.tpl");
    $tpl->assign('groups', $mod->getGroups());

    if (isset($options[1])) {
      switch($options[1]) {
        case ('order' && isset($options[4])):
          if ($options[3] == 'up') {
            $mod->moveUP($options[2],$options[4]);
          } else {
            $mod->moveDOWN($options[2],$options[4]);
          }
        break;
        case 'gorder':
          if ($options[3] == 'up') {
            $mod->gmoveUP($options[2]);
          } else {
            $mod->gmoveDOWN($options[2]);
          }
        break;
        case 'modify':
          $tpl->assign('modify', true);
          $mod->setId($options[2]);
        break;
        case 'delete':
          $tpl->assign('option_tpl',"$template/modules/$module/delete_module_group.tpl");
          $tpl->assign('id', (int)$options[2]);
          $tpl->assign('name', $options[3]);
          if ($options[3] == 'true') {
            $tpl->assign('result', true);
            $mod->SetId($options[2]);
            $mod->deleteGroup();
          }
        break;
      }
    }

    $form = new AddModuleGroup($tpl, $mod);
    if ($form->validate()) {
      $form->freeze();
      $form->process();
    } else {
      $form->displayForm();
    }
  break;
  default:
    /**
     * display all modules block
     */
    if(isset($_POST['display_all_modules'])) {
      $rs = $db->Execute("UPDATE core_config SET config_value=1-config_value WHERE config_name='display_all_modules'"); // toggle between 1 0
      header('refresh: 0; url=/admin/modules');
    }
    $tpl->assign('display_all_modules', ($db->getOne("SELECT config_value FROM core_config WHERE config_name='display_all_modules'") == 1) ? true : false);

    /**
    * Get all the modules read directory and crete array $modules
    */
    $dir = SITE_ROOT.'modules';
    $files = scandir($dir);
    $modules = array();
    foreach ($files as $data) {
     if (!preg_match('/^\./', $data)) {
       $inc = "$dir/$data/$data"."_module.php";
       if (file_exists($inc)) {
         require_once $inc;
         $modules[$data]['name'] = $data; // needed for Autoexec
         $modules[$data]['description'] = trim($module_description);
         $module_description = '';
       }
     }
    }

    /**
    * Clean up modules table (erase modules that have been moved or deleted)
    */
    $stored_modules = $db->GetCol("SELECT name FROM core_modules");
    $existing_modules = array_keys($modules);
    $modules_diff = array_diff($stored_modules, $existing_modules);
    foreach ($modules_diff as $value) {
     $rs = $db->Execute("DELETE FROM core_modules WHERE name='$value'");
    }

    foreach ($modules as $key => $value) {
     $rs = $db->GetRow("SELECT * FROM core_modules WHERE name='$key'");
     if(!$rs) {
       $rs = $db->AutoExecute('core_modules', $value, 'INSERT');
     } elseif ($value['description'] !=  $rs['description']) {
       $rs = $db->AutoExecute('core_modules', $value, 'UPDATE', "name='$key'");
     }
    }

    $tpl->assign('option_tpl',"$template/modules/$module/modules_status.tpl");
    $tpl->assign('modules', $db->GetAll("SELECT * FROM core_modules ORDER BY FIELD(name,'main','user','admin') DESC, name"));
  break;
}

?>